package com.lagou.config;

import com.lagou.bean.MapperStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于解析每个mapper.xml的,例如userMapper.xml
 */
public class XMLMapperBuilder {

    /**
     *
     * @param stream
     * @return id对应MapperStatement关系
     * @see com.lagou.bean.MapperStatement
     * @throws Exception
     */
    public Map<String, MapperStatement> parse(InputStream stream) throws Exception {
        Document document = new SAXReader().read(stream);
        Element rootElement = document.getRootElement();
        Map<String, MapperStatement> mapperMap = new HashMap<>();
        putMapper(rootElement, mapperMap, "select");
        putMapper(rootElement, mapperMap, "insert");
        putMapper(rootElement, mapperMap, "update");
        putMapper(rootElement, mapperMap, "delete");

        return mapperMap;
    }

    void putMapper(Element rootElement,  Map<String, MapperStatement> mapperMap, String str) throws Exception {
        List<Element> elements =  rootElement.selectNodes(str);
        String namespace = rootElement.attributeValue("namespace");
        for (Element item : elements) {
            // 以下开始解析每个select标签，并将其中每个属性放入一个MapperStatement对象中。
            String id = item.attributeValue("id");
            String paramterType = item.attributeValue("paramterType");
            String resultType = item.attributeValue("resultType");
            Class<?> paramterTypeClass = null;
            Class<?> resultTypeClass = null;
            if (paramterType != null) {
                paramterTypeClass = Class.forName(paramterType);
            }
            if (resultType != null) {
                resultTypeClass = Class.forName(resultType);
            }
            String key = namespace +"."+id;
            String textTrim = item.getTextTrim();

            //开始设置mapperStatement
            MapperStatement mappedStatement = new MapperStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterTypeClass);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setSql(textTrim);
            mapperMap.put(key, mappedStatement);
        }
    }
}
